//
//  CountdownViewModel.swift
//  test
//
//  Created by bianruifeng on 2025/7/6.
//


import RxSwift

class CountdownViewModel {
    private let disposeBag = DisposeBag()
    private var timer: Disposable?
    private let countdownSubject = BehaviorSubject<Int>(value: 30)
    
    var countdownObservable: Observable<Int> {
        return countdownSubject.asObservable()
    }
    
    init() {
        startCountdown()
    }
    
    private func startCountdown() {
        var remainingTime = 30
        
        // 每秒更新一次
        timer = Observable<Int>.interval(.seconds(1), scheduler: MainScheduler.instance)
            .subscribe(onNext: { [weak self] _ in
                if remainingTime > 0 {
                    self?.countdownSubject.onNext(remainingTime)
                    remainingTime -= 1
                } else {
                    remainingTime = 30 // 重置倒计时
                }
            })
    }
    
    func stopCountdown() {
        timer?.dispose() // 停止计时器
    }
}
